package com.lanan.springboot.controller.admin;

import com.lanan.springboot.controller.api.BaseApiController;
import com.lanan.springboot.exception.ApiException;
import com.lanan.springboot.util.Result;
import com.lanan.springboot.util.captcha.Randoms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LanAn
 * @date 2022/3/24-15:21
 * @Description TODO
 */
@RestController
@RequestMapping("/api/userCenter")
public class UserCenterMailController extends BaseApiController {
    private final String emailCode = "emailCode";
    private final String emailTime = "emailTime";

    @Autowired
    JavaMailSender javaMailSender;

    /**
     * @desc 读取配置文件邮箱账号参数
     **/
    @Value("${spring.mail.username}")
    private String sender;

    @Value("${email.time}")
    private String time;

    /**
     * @desc 发送待验证码的邮件
     * @author lanan
     * @date 2022-04-09 17:09:52
     * @param data
     * @param session
     * @return com.lanan.springboot.util.Result
     **/
    @PostMapping("/sendEmail")
    public Result sendEmail(@RequestBody Map<String, String> data, HttpSession session){
        String captchaCode = (String) session.getAttribute("_captcha");
        String em = data.get("email");
        String c = data.get("captcha");
        String email = StringUtils.isEmpty(em) ? null : em;
        String captcha = StringUtils.isEmpty(c) ? null : c;

        if (captchaCode == null || StringUtils.isEmpty(captcha) || !captchaCode.equalsIgnoreCase(captcha)) {
            throw new ApiException(502, "验证码错误");
        }
        if (email ==null) {
            throw new ApiException(501, "邮箱不能为空");
        }
        //随机数  用作验证
        String code = Randoms.randomGenerateRandomCode(6);
        try {
            //建立邮件消息
            SimpleMailMessage mainMessage = new SimpleMailMessage();
            //发送者
            mainMessage.setFrom(sender);
            //接收者
            mainMessage.setTo(email);
            //发送的标题
            mainMessage.setSubject("邮箱验证");
            //发送的内容
            String msg = "您好！" + email + ",您正在使用邮箱验证，验证码：" + code + " ,有效时间为30分钟。";
            mainMessage.setText(msg);
            javaMailSender.send(mainMessage);
        } catch (Exception e) {
            throw new ApiException("发送邮件失败，请核对邮箱账号");
        }
        //下面是加入缓存，以便于进行邮箱验证
        Map<String, Object> map = new HashMap<>(2);
        map.put("emailCode", code);
        map.put("emailTime", System.currentTimeMillis());
        session.setAttribute("email", map);
        return success("邮件发送成功");
    }
}
